﻿using EnetaMvc.Core.Repositories;
using EnetaMvc.Core.Domain.Content;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using EnetaMvc.Infrastructure;
using NHibernate.Criterion;

namespace EnetaMvc.Data.NHibernate.Repositories
{
    public class TagGroupRepository : BaseRepository, ITagGroupRepository
    {
        private readonly ISession _session;

        public TagGroupRepository(IMapperSession session)
            :base(((NHSession)session).GetCurrentSession())
        {
            _session = ((NHSession)session).GetCurrentSession();
        }

        public IList<TagGroup> ListTagGroups()
        {
            return _session.CreateCriteria<TagGroup>().List<TagGroup>();
        }

        public TagGroup GetTagGroupById(long id)
        {
            return _session.Get<TagGroup>(id);
        }

        public void SaveTagGroup(TagGroup tagGroup)
        {
            if (tagGroup == null)
                return;

            SaveInTransaction(tagGroup);
        }

        public void DeleteTagGroup(long id)
        {
            TagGroup tagGroup = GetTagGroupById(id);
            if (tagGroup == null)
                return;

            DeleteInTransaction(tagGroup);
        }

        public bool HasTags(long id)
        {
            var totalTagsForGroup = _session.CreateCriteria<Tag>()
                                        .Add(Expression.Eq("Group.Id", id))
                                        .List<Tag>()
                                        .Count;
            return (totalTagsForGroup > 0);
        }
    }
}
